const request = require('../request/index')

// 设置自动跳转的路由
const autoJumpRoutes = ['/', '/youxuan', '/temai']

// 自动跳转对应城市的搜索地址
async function autoJumpToCity(req, res, next) {
  // 判断是否是搜索引擎
  let userAgent = ''
  if (
    req.headers &&
    req.headers['user-agent'] &&
    typeof req.headers['user-agent'] === 'string'
  ) {
    userAgent = req.headers['user-agent'].toLowerCase()
  }
  if (
    ['baiduspider', 'googlebot', '360spider', 'sosospider', 'sogou'].some(
      item => (userAgent || '').includes(item)
    )
  ) {
    return next()
  }

  // 服务端直接访问没有session对象
  if (!req.session) {
    console.log('没有session对象')
    return next()
  }

  // 获取用户位置信息
  if (!req.session.city || !req.session.city.list) {
    const data = await request({
      url: '/api/hotel/web/v1/city',
      params: {
        ip: (
          req.headers['x-forwarded-for'] ||
          req.connection.remoteAddress ||
          req.socket.remoteAddress ||
          req.connection.socket.remoteAddress
        ).split(',')[0]
      }
    })
    // console.log('位置信息：', data)
    req.session.city = data
  }

  // 其他访问
  const path = req.originalUrl.split('?')[0]
  const routes = autoJumpRoutes
  if (routes.includes(path) && req.session && req.session.city) {
    const { region_code } = req.session.city.city
    const prefix =
      {
        320500: '/sz',
        310100: '/sh'
      }[region_code] || '/sz'
    if (prefix) {
      return res.redirect(302, `${prefix}${req.originalUrl}`)
    }
  }
  next()
}

module.exports = autoJumpToCity
